﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using QuickAppLibrary;

namespace WebApplicationFiller
{
    public partial class WebAppMainForm : Form
    {
        //Class Objects/Varibles
        WebBrowserExtensions browser;
        ApplicationInfo myInfo;
        AppFillerSubForm fillerForm;
        PriorEmployerCollection priorEmpColl;
        Point mouseLocation; //For contextual menu
        ToolStripSpringTextBox urlTextBox; //URL TextBox
        ToolStripButton goButton;
        
        private string homeURL = "https://qapply.codeplex.com";

        //Form Constructor, Initilzation for Class Objects done here
        public WebAppMainForm()
        {
            InitializeComponent();

            //Initilize FillerForm
            fillerForm = new AppFillerSubForm();

            //Initilize ApplicationInfo 
            myInfo = new ApplicationInfo();

            //Initilize the WebBrowserExtensions
            browser = new WebBrowserExtensions(webBrowser);

            //Initilize EmployerCollection
            priorEmpColl = new PriorEmployerCollection();

            //Set Web Browswer Contextual Menu
            browser.WebBrowser.ContextMenuStrip = webContextMenuStrip;

            //Setup the context menu
            SetUpContextMenu();

            SetupURLTextBox();

            SetupGoButton();
        }

        //Sets up URL Textbox
        private void SetupURLTextBox()
        {
            //Initilize and add a URL ToolStripSpringTextBox to Form
            urlTextBox = new ToolStripSpringTextBox();

            //Set an AutoComplete for textbox
            urlTextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            urlTextBox.AutoCompleteSource = AutoCompleteSource.AllUrl;

            //Set Properties
            urlTextBox.Height = 25;

            //Enter key Event handler
            urlTextBox.KeyDown += new KeyEventHandler(urlTextBox_KeyDown);

            //Add it to the toolstrip
            browserToolStrip.Items.Add(urlTextBox);
        }

        //Sets up go button
        private void SetupGoButton()
        {
            //Add the Go Button to the Form
            goButton = new ToolStripButton();

            //button properties
            goButton.ForeColor = Color.Green;
            goButton.AutoSize = false;
            goButton.Size = new Size(50, 25);
            goButton.Text = "Go";

            //button Event handlers
            goButton.Click += new EventHandler(goButton_Click);

            //Add it to the ToolStrip
            browserToolStrip.Items.Add(goButton);
        }

        //Sets up Contextual Menu
        private void SetUpContextMenu()
        {
            //First clear out the toolstrip menus to avoid possible duplications
            empHistToolStripMenuItem.DropDownItems.Clear();
            appInfoToolStripMenuItem.DropDownItems.Clear();

            //Get control collection
            Control.ControlCollection appTab = fillerForm.Controls["tabControl1"].Controls["AppTabPage"].Controls;
            Control.ControlCollection priorEmplTab = fillerForm.Controls["tabControl1"].Controls["priorEmplTabPage"].Controls;

            foreach(Control con in appTab)
            {
                if (con is TextBox && con.Text != "")
                {
                    appInfoToolStripMenuItem.DropDownItems.Add(con.Text, null, new EventHandler(OnContextMenuSelected));
                }
            }

            
            //Call again to insure collection is collected
            priorEmpColl = fillerForm.getPriorEmpColl();

            ToolStripMenuItem empHistSubStrip;

            //Loop through list & properties to add context menu information
            foreach (PriorEmployer emp in priorEmpColl)
            {
                empHistSubStrip = new ToolStripMenuItem();
                empHistSubStrip.Text = emp.ToString();
                foreach (System.Reflection.PropertyInfo prop in emp.GetType().GetProperties())
                {
                    try
                    {
                        if (prop.GetValue(emp, null).ToString() != "")
                        {
                            empHistSubStrip.DropDownItems.Add(prop.GetValue(emp, null).ToString(), null, new EventHandler(OnContextMenuSelected));
                        }
                    }
                    catch (NullReferenceException ex)
                    {
                        MessageBox.Show(ex.StackTrace);
                    }
                }
                //Add to dropdown list on empHist tool strip
                empHistToolStripMenuItem.DropDownItems.Add(empHistSubStrip);
            }
        }

        //Event Handler for Context Menus
        private void OnContextMenuSelected(object sender, EventArgs e)
        {
            try
            {
                HtmlElement elem = webBrowser.Document.GetElementFromPoint(mouseLocation);

                if (elem.TagName.ToLower() == "input")
                {
                    elem.InnerText = sender.ToString();
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void goButton_Click(object sender, EventArgs e)
        {
            browser.Navigate(urlTextBox.Text);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void urlTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                webBrowser.Navigate(urlTextBox.Text);
            }
        }

        //Once the main form loads
        private void WebApp_Load(object sender, EventArgs e)
        {
            browser.Navigate(homeURL);
            urlTextBox.Text = homeURL;
        }

        //Fills out Application Info
        private void pasteApplicationButton_Click(object sender, EventArgs e)
        {
            //Get latests appliction info
            myInfo = fillerForm.getAppInfo();
            //Fill that info
            browser.FillApplication(myInfo);
        }

        private void pasteBioButton_Click(object sender, EventArgs e)
        {
            //Get latests appliction info
            myInfo = fillerForm.getAppInfo();
            //Fill Resume & Cover Letter Info
            browser.FillResume(myInfo);
        }

        //Browser Forward Button
        private void forwardButton_Click(object sender, EventArgs e)
        {
            webBrowser.GoForward();
        }

        //Browser Back Button
        private void backButton_Click(object sender, EventArgs e)
        {
            webBrowser.GoBack();
        }

        //Event - loads application form data
        private void setInfoButton_Click(object sender, EventArgs e)
        {
            try
            {
                //If it has been closed/disposed, open it
                if (fillerForm.IsDisposed)
                {
                    fillerForm = new AppFillerSubForm();
                }
                fillerForm.Show();
            }
            catch (ObjectDisposedException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //Exit button for main tool strip
        private void exitToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        /* Lost Code? - Poorly documented and not used
        private void infoTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode thisNode = e.Node;
            Control fillerTabs = fillerForm.Controls["tabControl1"];

            for(int i = 0; i < fillerTabs.Controls.Count; i++)
            {
                for (int k = 0; k < fillerTabs.Controls[i].Controls.Count; k++)
                {
                    if (fillerTabs.Controls[i].Controls[k].Name == thisNode.Text)
                    {
                        Clipboard.SetText(fillerTabs.Controls[i].Controls[k].Text);
                    }
                }
            }
        }
        */

        //Context Menu Opening
        private void webContextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            //Make sure the filler form is not disposed before attempting to use it
            if (fillerForm.IsDisposed)
            {
                fillerForm = new AppFillerSubForm();
            }
            //Reload the context menu, gets most recent info
            SetUpContextMenu();

            //Get Mouse position
            mouseLocation = webBrowser.PointToClient(MousePosition);
        }

        //Clears out a input text element in the browser
        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                HtmlElement elem = webBrowser.Document.GetElementFromPoint(mouseLocation);
                if (elem.TagName == "INPUT")
                {
                    elem.SetAttribute("value", "");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void coverToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                HtmlElement elem = webBrowser.Document.GetElementFromPoint(mouseLocation);
                elem.InnerText = myInfo.coverLetter;
            }
            catch (Exception ex)
            {
            }
        }

        private void resumeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                HtmlElement elem = webBrowser.Document.GetElementFromPoint(mouseLocation);
                elem.InnerText = myInfo.resumeText;
            }
            catch (Exception ex)
            {
            }
        }

        //Fills out former employers section
        private void pasteEmployerButton_Click(object sender, EventArgs e)
        {
            //Load the prior employeer collection
            priorEmpColl = fillerForm.getPriorEmpColl();
            //Fill out the browser
            browser.FillEmployers(priorEmpColl);
        }

        //Web Browser has completely loaded
        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //Set Name to webpage
            this.Text = webBrowser.DocumentTitle;

            //Reset Progress bar
            browserProgressBar.Value = 0;
        }

        //TODO - Create an "About" dialog
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form aboutBox = new Form();
            aboutBox.Text = "About";
            TextBox infoLabel = new TextBox();
            infoLabel.Text = "Learn More at: https://qapply.codeplex.com \n More Content to be added";
            infoLabel.Multiline = true;
            infoLabel.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
            infoLabel.Size = new System.Drawing.Size(300, 200);
            infoLabel.ReadOnly = true;
            aboutBox.Controls.Add(infoLabel);
            aboutBox.ShowDialog();
        }

        //Closing the form
        private void WebAppMainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Make sure the fillerForm gets closed too
            fillerForm.Close();
        }

        //Shows the Document Object Model
        private string PrintDOM(HtmlElementCollection elemColl, System.Text.StringBuilder returnStr, Int32 depth)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder();

            foreach (HtmlElement elem in elemColl)
            {
                string elemName;

                elemName = elem.TagName;

                if (elem.TagName.ToLower() == "input")
                {

                    str.Append(elemName + ": " + elem.Id);
                    returnStr.AppendLine(str.ToString());
                }

                if (elem.CanHaveChildren)
                {
                    PrintDOM(elem.Children, returnStr, depth + 1);
                }

                str.Remove(0, str.Length);
            }

            return (returnStr.ToString());
        }

        //Method to enable the toolstip menu
        static bool statusEnabled = false;
        private void statusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (statusEnabled == true)
            {
                statusEnabled = false;
                statusBarToolStripMenuItem.Text = "Status bar";
                //webBrowser.ClientSize = new Size(900, 480);
            }
            else if (statusEnabled == false)
            {
                statusEnabled = true;
                statusBarToolStripMenuItem.Text = "Status bar ✓";
                //webBrowser.ClientSize = new Size(900, 460);
            }
            browserStatusStrip.Visible = statusEnabled;
            this.Update();
        }

        //Event handler for progress in browser
        private void webBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            //Set the progress bar's Max value
            browserProgressBar.Maximum = (int) e.MaximumProgress;

            //Check that the progress bar's value dosen't go out of range
            if (e.CurrentProgress > browserProgressBar.Minimum && e.CurrentProgress < browserProgressBar.Maximum)
            {
                browserProgressBar.Value = (int)e.CurrentProgress;
            }
        }

        //Opens the Help System
        private void helpToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }

        //Reset Zooming on Browser
        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Sets the focus of the browser and uses a shortcut to reset zooming
            browser.WebBrowser.Focus();
            SendKeys.Send("^0");
        }

        //Zoom in on the browser
        private void zoomInToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Sets the focus of the browser and uses a shortcut to zoom in
            browser.WebBrowser.Focus();
            SendKeys.Send("^{+}");
        }

        //Zoom out of the browser
        private void zoomOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Sets the focus of the browser and uses a shortcut to zoom out
            browser.WebBrowser.Focus();
            SendKeys.Send("^-");
        }
    }
}
